import React, { useState, useEffect } from 'react';
import {
  Tabs,
  Card,
  Row,
  Col,
  Form,
  Input,
  InputNumber,
  Button,
  Table,
  Space,
  Typography,
  Tag,
  Statistic,
  theme,
  DatePicker,
} from 'antd';
import { useWindowSize } from '../hooks/useWindowSize';
import MobileTimeRangePicker from '../components/MobileTimeRangePicker';
import {
  DatabaseOutlined,
  ExperimentOutlined,
  SettingOutlined,
  SearchOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { dataAPI } from '../services/api';
import dayjs from 'dayjs';

const { Title, Text } = Typography;

const DataQuery = () => {
  const { t } = useTranslation();
  const { token } = theme.useToken();
  const { isMobile } = useWindowSize();
  const [activeTab, setActiveTab] = useState('deviceData');
  const [loading, setLoading] = useState(false);
  const [deviceData, setDeviceData] = useState([]);
  const [tempHumidityData, setTempHumidityData] = useState([]);
  const [deviceParams, setDeviceParams] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 搜索表单状态
  const [searchVisible, setSearchVisible] = useState(true);
  const [nextRefreshTime, setNextRefreshTime] = useState(null);
  const [deviceDataForm] = Form.useForm();
  const [tempHumidityForm] = Form.useForm();
  const [deviceParamsForm] = Form.useForm();

  // 保存当前搜索条件的状态
  const [currentSearchParams, setCurrentSearchParams] = useState({
    deviceData: {},
    tempHumidity: {},
    deviceParams: {}
  });


  // 时间格式化函数
  const formatTimestamp = (timestamp, format = 'YYYY-MM-DD HH:mm:ss') => {
    if (!timestamp) return '-';

    if (typeof timestamp === 'number') {
      // 如果是10位数字，说明是秒级时间戳
      if (timestamp.toString().length === 10) {
        return dayjs.unix(timestamp).format(format);
      }
      // 如果是13位数字，说明是毫秒级时间戳
      else if (timestamp.toString().length === 13) {
        return dayjs(timestamp).format(format);
      }
    }
    // 处理字符串格式的时间
    return dayjs(timestamp).format(format);
  };

  // 设备数据表格列
  const deviceDataColumns = [
    {
      title: t('data.sampleCode'),
      dataIndex: 'sample',
      key: 'sample',
      width: 100,
    },
    {
      title: t('data.gatewayBatch'),
      dataIndex: 'waybatch',
      key: 'waybatch',
      width: 150,
    },
    {
      title: t('data.gatewayCode'),
      dataIndex: 'waycode',
      key: 'waycode',
      width: 120,
    },
    {
      title: t('data.batchNumber'),
      dataIndex: 'batch',
      key: 'batch',
      width: 120,
    },
    {
      title: t('data.deviceCode'),
      dataIndex: 'code',
      key: 'code',
      width: 120,
    },
    {
      title: t('data.voltage') + '（V）',
      dataIndex: 'voltage',
      key: 'voltage',
      width: 100,
      render: (value) => value ? `${(value / 100).toFixed(2)}` : '-',
    },
    {
      title: t('data.measureValue'),
      dataIndex: 'mesa',
      key: 'mesa',
      width: 120,
    },
    {
      title: t('data.angle'),
      dataIndex: 'angle',
      key: 'angle',
      width: 100,
      render: (value) => value ? `${value}°` : '-',
    },
    {
      title: t('data.chipTemperature') + '（°C）',
      dataIndex: 'tmp',
      key: 'tmp',
      width: 120,
      render: (value) => value ? `${(value / 100).toFixed(1)}` : '-',
    },
    {
      title: t('data.signalStrength') + '（dBm）',
      dataIndex: 'rssi',
      key: 'rssi',
      width: 120,
      render: (value) => value ? `${value}` : '-',
    },
    {
      title: '时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (updatedAt) => formatTimestamp(updatedAt),
    },
  ];

  // 温湿度数据表格列
  const tempHumidityColumns = [
    {
      title: t('data.sampleCode'),
      dataIndex: 'sample',
      key: 'sample',
      width: 100,
    },
    {
      title: t('data.batchNumber'),
      dataIndex: 'batch',
      key: 'batch',
      width: 120,
    },
    {
      title: t('data.deviceCode'),
      dataIndex: 'code',
      key: 'code',
      width: 120,
    },
    {
      title: t('data.temperature') + '（°C）',
      dataIndex: 'temp',
      key: 'temp',
      width: 100,
      render: (value) => value ? `${(value / 100).toFixed(1)}` : '-',
    },
    {
      title: t('data.humidity') + '（%）',
      dataIndex: 'humi',
      key: 'humi',
      width: 100,
      render: (value) => value ? `${(value / 100).toFixed(1)}` : '-',
    },
    {
      title: '时间',
      dataIndex: 'simpletime',
      key: 'simpletime',
      width: 180,
      render: (timestamp) => formatTimestamp(timestamp),
    },
  ];

  // 设备参数表格列 - 横向显示
  const getDeviceParamsColumns = () => {
    return [
      {
        title: '设备编号',
        dataIndex: 'code',
        key: 'code',
        width: 100,
        fixed: 'left',
      },
      {
        title: '扫描时间（秒）',
        dataIndex: 'scanTime',
        key: 'scanTime',
        width: 100,
        render: (value) => value ? `${value}` : '-',
      },
      {
        title: '网络超时（毫秒）',
        dataIndex: 'netOverTime',
        key: 'netOverTime',
        width: 120,
        render: (value) => value ? `${value}` : '-',
      },
      {
        title: '唤醒间隔（秒）',
        dataIndex: 'waywakeup',
        key: 'waywakeup',
        width: 100,
        render: (value) => value ? `${value}` : '-',
      },
      {
        title: '下次唤醒',
        dataIndex: 'nextwakeup',
        key: 'nextwakeup',
        width: 160,
        render: (value) => value ? formatTimestamp(value, 'YYYY-MM-DD HH:mm:ss') : '-',
      },
      {
        title: '发射功率（dBm）',
        dataIndex: 'dbpower',
        key: 'dbpower',
        width: 100,
        render: (value) => value !== undefined ? `${value}` : '-',
      },
      {
        title: '软件版本',
        dataIndex: 'software',
        key: 'software',
        width: 120,
        render: (value) => value ? value.replace(/\u0000/g, '') : '-',
      },
      {
        title: '硬件版本',
        dataIndex: 'hardware',
        key: 'hardware',
        width: 120,
        render: (value) => value ? value.replace(/\u0000/g, '') : '-',
      },
      {
        title: 'IMSI',
        dataIndex: 'imsi',
        key: 'imsi',
        width: 140,
        render: (value) => value ? <Text code>{value}</Text> : '-',
      },
      {
        title: '更新时间',
        dataIndex: 'updatedAt',
        key: 'updatedAt',
        width: 160,
        render: (value) => value ? formatTimestamp(value, 'YYYY-MM-DD HH:mm:ss') : '-',
      },
    ];
  };

  // 获取设备数据
  const fetchDeviceData = async (params = {}, paginationParams = null) => {
    const currentPagination = paginationParams || pagination;
    setLoading(true);
    try {
      const response = await dataAPI.getDeviceDataList({
        pageNo: currentPagination.current,
        pageSize: currentPagination.pageSize,
        pageOrderName: 'id',
        pageOrderBy: 'desc',
        ...params,
      });

      if (response && response.data) {
        // 确保每条数据都有唯一的id
        const processedDeviceData = (response.data.list || []).map((item, index) => ({
          ...item,
          id: item.id || item.code || `device_data_${index}_${Date.now()}`
        }));
        setDeviceData(processedDeviceData);
        setPagination(prev => ({
          ...prev,
          current: currentPagination.current,
          pageSize: currentPagination.pageSize,
          total: response.data.totalCount || response.data.total || 0,
        }));
      }
    } catch (error) {
      console.error('获取设备数据错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取温湿度数据
  const fetchTempHumidityData = async (params = {}, paginationParams = null) => {
    const currentPagination = paginationParams || pagination;
    setLoading(true);
    try {
      const response = await dataAPI.getDeviceTmpRHList({
        pageNo: currentPagination.current,
        pageSize: currentPagination.pageSize,
        pageOrderName: 'id',
        pageOrderBy: 'desc',
        ...params,
      });

      if (response && response.data) {
        // 确保每条数据都有唯一的id
        const processedTempData = (response.data.list || []).map((item, index) => ({
          ...item,
          id: item.id || item.code || `temp_data_${index}_${Date.now()}`
        }));
        setTempHumidityData(processedTempData);
        setPagination(prev => ({
          ...prev,
          current: currentPagination.current,
          pageSize: currentPagination.pageSize,
          total: response.data.totalCount || response.data.total || 0,
        }));
      }
    } catch (error) {
      console.error('获取温湿度数据错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取设备参数
  const fetchDeviceParams = async (params = {}, paginationParams = null) => {
    const currentPagination = paginationParams || pagination;
    setLoading(true);
    try {
      const response = await dataAPI.getDeviceParamList({
        pageNo: currentPagination.current,
        pageSize: currentPagination.pageSize,
        pageOrderName: 'id',
        pageOrderBy: 'desc',
        ...params,
      });

      if (response && response.data) {
        // 解析每个设备的参数数据
        const processedData = (response.data.list || []).map((device, index) => {
          let parsedParams = {};

          try {
            if (device.param) {
              parsedParams = JSON.parse(device.param);
            }
          } catch (error) {
            console.error('解析设备参数失败:', error);
          }

          return {
            id: device.id || device.code || `device_${index}_${Date.now()}`, // 确保每行都有唯一ID
            code: device.code,
            scanTime: parsedParams.scanTime,
            netOverTime: parsedParams.netOverTime,
            waywakeup: parsedParams.waywakeup,
            nextwakeup: parsedParams.nextwakeup,
            dbpower: parsedParams.dbpower,
            software: device.software,
            hardware: device.hardware,
            imsi: device.imsi,
            updatedAt: device.updatedAt,
          };
        });

        setDeviceParams(processedData);
        setPagination(prev => ({
          ...prev,
          current: currentPagination.current,
          pageSize: currentPagination.pageSize,
          total: response.data.totalCount || response.data.total || 0,
        }));
      }
    } catch (error) {
      console.error('获取设备参数错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 处理表格变化
  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
    // 根据当前标签页重新获取数据，并携带当前的搜索条件和新的分页参数
    switch (activeTab) {
      case 'deviceData':
        fetchDeviceData(currentSearchParams.deviceData, newPagination);
        break;
      case 'tempHumidity':
        fetchTempHumidityData(currentSearchParams.tempHumidity, newPagination);
        break;
      case 'deviceParams':
        fetchDeviceParams(currentSearchParams.deviceParams, newPagination);
        break;
      default:
        break;
    }
  };

  // 处理搜索参数，转换时间范围
  const processSearchParams = (params) => {
    const processedParams = { ...params };

    // 处理时间范围
    if (processedParams.timeRange && processedParams.timeRange.length === 2) {
      const [startTime, endTime] = processedParams.timeRange;
      processedParams.timeStart = Math.floor(startTime.valueOf() / 1000); // 转为秒级时间戳
      processedParams.timeEnd = Math.floor(endTime.valueOf() / 1000); // 转为秒级时间戳
      delete processedParams.timeRange; // 删除原始时间范围字段
    }

    // 过滤掉空值
    Object.keys(processedParams).forEach(key => {
      if (processedParams[key] === undefined || processedParams[key] === null || processedParams[key] === '') {
        delete processedParams[key];
      }
    });

    return processedParams;
  };

  // 处理搜索
  const handleSearch = () => {
    setPagination(prev => ({ ...prev, current: 1 }));

    switch (activeTab) {
      case 'deviceData':
        const deviceSearchParams = deviceDataForm.getFieldsValue();
        const processedDeviceParams = processSearchParams(deviceSearchParams);
        // 保存搜索条件
        setCurrentSearchParams(prev => ({
          ...prev,
          deviceData: processedDeviceParams
        }));
        fetchDeviceData(processedDeviceParams);
        break;
      case 'tempHumidity':
        const tempSearchParams = tempHumidityForm.getFieldsValue();
        const processedTempParams = processSearchParams(tempSearchParams);
        // 保存搜索条件
        setCurrentSearchParams(prev => ({
          ...prev,
          tempHumidity: processedTempParams
        }));
        fetchTempHumidityData(processedTempParams);
        break;
      case 'deviceParams':
        const paramsSearchParams = deviceParamsForm.getFieldsValue();
        const processedParamsParams = processSearchParams(paramsSearchParams);
        // 保存搜索条件
        setCurrentSearchParams(prev => ({
          ...prev,
          deviceParams: processedParamsParams
        }));
        fetchDeviceParams(processedParamsParams);
        break;
      default:
        break;
    }
  };

  // 重置搜索
  const handleReset = () => {
    switch (activeTab) {
      case 'deviceData':
        deviceDataForm.resetFields();
        // 清空搜索条件
        setCurrentSearchParams(prev => ({
          ...prev,
          deviceData: {}
        }));
        fetchDeviceData();
        break;
      case 'tempHumidity':
        tempHumidityForm.resetFields();
        // 清空搜索条件
        setCurrentSearchParams(prev => ({
          ...prev,
          tempHumidity: {}
        }));
        fetchTempHumidityData();
        break;
      case 'deviceParams':
        deviceParamsForm.resetFields();
        // 清空搜索条件
        setCurrentSearchParams(prev => ({
          ...prev,
          deviceParams: {}
        }));
        fetchDeviceParams();
        break;
      default:
        break;
    }
  };

  // 处理标签页切换
  const handleTabChange = (key) => {
    setActiveTab(key);
    setPagination(prev => ({ ...prev, current: 1 }));
    // 保持搜索框展开状态，不隐藏

    switch (key) {
      case 'deviceData':
        fetchDeviceData();
        break;
      case 'tempHumidity':
        fetchTempHumidityData();
        break;
      case 'deviceParams':
        fetchDeviceParams();
        break;
      default:
        break;
    }
  };

  useEffect(() => {
    // 首次加载，根据默认标签页获取数据
    fetchDeviceData();
  }, []);

  // 自动刷新功能 - 每10分钟刷新一次
  useEffect(() => {
    // 设置下次刷新时间
    const setRefreshTime = () => {
      const nextTime = new Date();
      nextTime.setMinutes(nextTime.getMinutes() + 10);
      setNextRefreshTime(nextTime);
    };

    setRefreshTime();

    // 设置定时器，每10分钟执行一次
    const interval = setInterval(() => {
      console.log('自动刷新数据查询页面数据...');
      // 根据当前活跃标签页刷新对应数据，并携带搜索条件
      switch (activeTab) {
        case 'deviceData':
          fetchDeviceData(currentSearchParams.deviceData);
          break;
        case 'tempHumidity':
          fetchTempHumidityData(currentSearchParams.tempHumidity);
          break;
        case 'deviceParams':
          fetchDeviceParams(currentSearchParams.deviceParams);
          break;
        default:
          break;
      }
      setRefreshTime();
    }, 10 * 60 * 1000); // 10分钟 = 10 * 60 * 1000毫秒

    // 清理定时器
    return () => {
      clearInterval(interval);
    };
  }, [activeTab, currentSearchParams]); // 依赖activeTab和currentSearchParams，当标签切换或搜索条件改变时重新设置定时器


  // 获取当前数据
  const getCurrentData = () => {
    switch (activeTab) {
      case 'deviceData':
        return deviceData;
      case 'tempHumidity':
        return tempHumidityData;
      case 'deviceParams':
        return deviceParams;
      default:
        return [];
    }
  };

  // 获取当前列
  // 移动端列配置 - 针对性优化
  const getMobileColumns = (columns) => {
    if (!isMobile) return columns;

    return columns.map(col => {
      // 根据列的内容类型设置不同的宽度策略
      let mobileWidth;

      // 针对不同字段优化宽度
      if (col.dataIndex === 'sample') {
        // 样地编号 - 通常是数字，可以很窄
        mobileWidth = 45;
      } else if (col.dataIndex === 'batch' || col.dataIndex === 'code') {
        // 批次号和设备编号 - 适中宽度
        mobileWidth = 55;
      } else if (col.dataIndex === 'temp' || col.dataIndex === 'humi') {
        // 温度和湿度 - 格式化后较短
        mobileWidth = 50;
      } else if (col.dataIndex === 'simpletime' || col.dataIndex === 'updatedAt') {
        // 时间字段 - 需要更多空间但可以压缩
        mobileWidth = 85;
      } else {
        // 其他字段 - 默认压缩到35%
        mobileWidth = col.width ? Math.max(col.width * 0.35, 45) : 50;
      }

      return {
        ...col,
        width: mobileWidth,
        render: col.render ? col.render : (text) => (
          <span style={{
            fontSize: '10px',
            lineHeight: '1.1',
            wordBreak: 'break-all',
            display: 'block',
            overflow: 'hidden'
          }}>
            {text}
          </span>
        ),
      };
    }); // 显示所有列，用户可以横向滚动查看
  };

  const getCurrentColumns = () => {
    let columns = [];
    switch (activeTab) {
      case 'deviceData':
        columns = deviceDataColumns;
        break;
      case 'tempHumidity':
        columns = tempHumidityColumns;
        break;
      case 'deviceParams':
        columns = getDeviceParamsColumns();
        break;
      default:
        columns = [];
    }

    return getMobileColumns(columns);
  };

  // 渲染搜索表单
  const renderSearchForm = () => {
    const formStyle = {
      background: token.colorBgContainer,
      border: `1px solid ${token.colorBorder}`,
      borderRadius: 8,
      padding: 16,
      marginBottom: 16,
    };

    switch (activeTab) {
      case 'deviceData':
        return (
          <Card size="small" style={formStyle}>
            <Form
              form={deviceDataForm}
              layout="inline"
              style={{ width: '100%' }}
              onFinish={handleSearch}
            >
              <Row gutter={[16, 16]} style={{ width: '100%' }}>
                <Col xs={24} sm={12} md={8} lg={6} xl={4}>
                  <Form.Item label="样地编号" name="sample">
                    <InputNumber placeholder="请输入样地编号" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12} md={8} lg={6} xl={4}>
                  <Form.Item label="网关批次" name="waybatch">
                    <InputNumber placeholder="请输入网关批次" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12} md={8} lg={6} xl={4}>
                  <Form.Item label="网关编号" name="waycode">
                    <InputNumber placeholder="请输入网关编号" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12} md={8} lg={6} xl={4}>
                  <Form.Item label="设备批次" name="batch">
                    <InputNumber placeholder="请输入设备批次" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12} md={8} lg={6} xl={4}>
                  <Form.Item label="设备编号" name="code">
                    <InputNumber placeholder="请输入设备编号" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={24} md={16} lg={12} xl={8}>
                  <Form.Item label="时间范围" name="timeRange">
                    {isMobile ? (
                      <MobileTimeRangePicker
                        placeholder={['开始时间', '结束时间']}
                      />
                    ) : (
                      <DatePicker.RangePicker
                        style={{ width: '100%' }}
                        placeholder={['开始时间', '结束时间']}
                        showTime={{ format: 'HH:mm:ss' }}
                        format="YYYY-MM-DD HH:mm:ss"
                      />
                    )}
                  </Form.Item>
                </Col>
                <Col xs={24} sm={24} md={24} lg={24} xl={24}>
                  <div style={{ textAlign: 'left', marginTop: '8px' }}>
                    <Space>
                      <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                        查询
                      </Button>
                      <Button onClick={handleReset}>
                        重置
                      </Button>
                    </Space>
                  </div>
                </Col>
              </Row>
            </Form>
          </Card>
        );

      case 'tempHumidity':
        return (
          <Card size="small" style={formStyle}>
            <Form
              form={tempHumidityForm}
              layout="inline"
              style={{ width: '100%' }}
              onFinish={handleSearch}
            >
              <Row gutter={[16, 16]} style={{ width: '100%' }}>
                <Col xs={24} sm={12} md={8} lg={6} xl={5}>
                  <Form.Item label="样地编号" name="sample">
                    <InputNumber placeholder="请输入样地编号" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12} md={8} lg={6} xl={5}>
                  <Form.Item label="设备批次" name="batch">
                    <InputNumber placeholder="请输入设备批次" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12} md={8} lg={6} xl={5}>
                  <Form.Item label="设备编号" name="code">
                    <InputNumber placeholder="请输入设备编号" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={24} md={16} lg={12} xl={9}>
                  <Form.Item label="时间范围" name="timeRange">
                    {isMobile ? (
                      <MobileTimeRangePicker
                        placeholder={['开始时间', '结束时间']}
                      />
                    ) : (
                      <DatePicker.RangePicker
                        style={{ width: '100%' }}
                        placeholder={['开始时间', '结束时间']}
                        showTime={{ format: 'HH:mm:ss' }}
                        format="YYYY-MM-DD HH:mm:ss"
                      />
                    )}
                  </Form.Item>
                </Col>
                <Col xs={24} sm={24} md={24} lg={24} xl={24}>
                  <div style={{ textAlign: 'left', marginTop: '8px' }}>
                    <Space>
                      <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                        查询
                      </Button>
                      <Button onClick={handleReset}>
                        重置
                      </Button>
                    </Space>
                  </div>
                </Col>
              </Row>
            </Form>
          </Card>
        );

      case 'deviceParams':
        return (
          <Card size="small" style={formStyle}>
            <Form
              form={deviceParamsForm}
              layout="inline"
              style={{ width: '100%' }}
              onFinish={handleSearch}
            >
              <Row gutter={[16, 16]} style={{ width: '100%' }}>
                <Col xs={24} sm={12} md={8} lg={6} xl={4}>
                  <Form.Item label="样地编号" name="sample">
                    <InputNumber placeholder="请输入样地编号" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12} md={8} lg={6} xl={4}>
                  <Form.Item label="设备批次" name="batch">
                    <InputNumber placeholder="请输入设备批次" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12} md={8} lg={6} xl={4}>
                  <Form.Item label="设备编号" name="code">
                    <InputNumber placeholder="请输入设备编号" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={12} md={8} lg={6} xl={4}>
                  <Form.Item label="IMSI" name="imsi">
                    <Input placeholder="请输入IMSI" style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col xs={24} sm={24} md={16} lg={12} xl={8}>
                  <Form.Item label="时间范围" name="timeRange">
                    {isMobile ? (
                      <MobileTimeRangePicker
                        placeholder={['开始时间', '结束时间']}
                      />
                    ) : (
                      <DatePicker.RangePicker
                        style={{ width: '100%' }}
                        placeholder={['开始时间', '结束时间']}
                        showTime={{ format: 'HH:mm:ss' }}
                        format="YYYY-MM-DD HH:mm:ss"
                      />
                    )}
                  </Form.Item>
                </Col>
                <Col xs={24} sm={24} md={24} lg={24} xl={24}>
                  <div style={{ textAlign: 'left', marginTop: '8px' }}>
                    <Space>
                      <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                        查询
                      </Button>
                      <Button onClick={handleReset}>
                        重置
                      </Button>
                    </Space>
                  </div>
                </Col>
              </Row>
            </Form>
          </Card>
        );

      default:
        return null;
    }
  };


  return (
    <div>
      <Row justify="space-between" align="middle" style={{ marginBottom: 24 }}>
        <Col>
          <Space align="center">
            <DatabaseOutlined style={{ fontSize: 24, color: '#faad14' }} />
            <Title level={2} style={{ margin: 0 }}>
              {t('data.title')}
            </Title>
          </Space>
        </Col>
        <Col>
          <Space>
            <Button
              icon={<SearchOutlined />}
              size={isMobile ? 'small' : 'large'}
              style={{
                borderRadius: 8,
                height: isMobile ? 28 : 40,
                paddingLeft: isMobile ? 12 : 20,
                paddingRight: isMobile ? 12 : 20,
                fontSize: isMobile ? '12px' : '14px',
              }}
              onClick={() => setSearchVisible(!searchVisible)}
            >
              {searchVisible ? '隐藏搜索' : '高级搜索'}
            </Button>
            <Button
              icon={<ReloadOutlined />}
              size={isMobile ? 'small' : 'large'}
              style={{
                borderRadius: 8,
                height: isMobile ? 28 : 40,
                paddingLeft: isMobile ? 12 : 20,
                paddingRight: isMobile ? 12 : 20,
                fontSize: isMobile ? '12px' : '14px',
              }}
              onClick={() => {
                switch (activeTab) {
                  case 'deviceData':
                    fetchDeviceData(currentSearchParams.deviceData);
                    break;
                  case 'tempHumidity':
                    fetchTempHumidityData(currentSearchParams.tempHumidity);
                    break;
                  case 'deviceParams':
                    fetchDeviceParams(currentSearchParams.deviceParams);
                    break;
                  default:
                    break;
                }
              }}
            >
              刷新
            </Button>
            {nextRefreshTime && (
              <div style={{ textAlign: 'right', marginLeft: 16 }}>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  🔄 下次刷新: {dayjs(nextRefreshTime).format('HH:mm:ss')}
                </Text>
                <br />
                <Text type="secondary" style={{ fontSize: '11px' }}>
                  平均采集间隔: 10分钟
                </Text>
              </div>
            )}
          </Space>
        </Col>
      </Row>

      <Tabs
        activeKey={activeTab}
        onChange={handleTabChange}
        items={[
          {
            key: 'deviceData',
            label: (
              <Space>
                <DatabaseOutlined />
                {t('data.deviceData')}
              </Space>
            ),
          },
          {
            key: 'tempHumidity',
            label: (
              <Space>
                <ExperimentOutlined />
                {t('data.temperatureHumidity')}
              </Space>
            ),
          },
          {
            key: 'deviceParams',
            label: (
              <Space>
                <SettingOutlined />
                {t('data.deviceParams')}
              </Space>
            ),
          },
        ]}
      />

      {/* 搜索表单 */}
      {searchVisible && renderSearchForm()}

      <div style={{ marginTop: 24 }}>
        <Row gutter={isMobile ? [8, 8] : [16, 16]} style={{ marginBottom: isMobile ? 8 : 16 }}>
          <Col span={12}>
            <Card size="small" bodyStyle={{ padding: isMobile ? '8px 12px' : '12px 16px' }}>
              <Statistic
                title="总数据量"
                value={pagination.total}
                valueStyle={{
                  color: '#1890ff',
                  fontSize: isMobile ? '16px' : '20px',
                }}
                titleStyle={{
                  fontSize: isMobile ? '11px' : '14px',
                }}
              />
            </Card>
          </Col>
          <Col span={12}>
            <Card size="small" bodyStyle={{ padding: isMobile ? '8px 12px' : '12px 16px' }}>
              <Statistic
                title="平均采集间隔"
                value={10}
                valueStyle={{
                  color: '#faad14',
                  fontSize: isMobile ? '16px' : '20px',
                }}
                titleStyle={{
                  fontSize: isMobile ? '11px' : '14px',
                }}
                suffix="分钟"
              />
            </Card>
          </Col>
        </Row>

        <Table
          columns={getCurrentColumns()}
          dataSource={getCurrentData()}
          rowKey="id"
          loading={loading}
          size={isMobile ? 'small' : 'middle'}
          pagination={isMobile ? {
            ...pagination,
            showSizeChanger: false,
            showQuickJumper: false,
            showTotal: (total, range) => `${range[0]}-${range[1]}/${total}`,
            simple: true,
            size: 'small',
          } : {
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `${t('common.total')} ${range[0]}-${range[1]} ${t('common.items')}/${total} ${t('common.items')}`,
          }}
          onChange={handleTableChange}
          scroll={{ x: isMobile ? 600 : 1200 }}
          style={{
            borderRadius: 8,
          }}
        />
      </div>
    </div>
  );
};

export default DataQuery;
